"""
单例模式：类能且仅能创建一个对象（实例）的模式
"""


class MyLove(object):
    # 心爱的人
    __instance = None
    __is_first_init = True

    def __new__(cls, *args, **kwargs):
        if MyLove.__instance is None:
            # 保证创建对象的唯一性
            MyLove.__instance = super().__new__(cls)
        return MyLove.__instance

    def __init__(self, girl):
        if MyLove.__is_first_init:
            self.__love = girl
            print('love: %s' % self.__love)
            MyLove.__is_first_init = False
        else:
            print('love: %s, do not love %s' % (self.__love, girl))

    def get_lover(self):
        print('love: ' + self.__love)
        return self.__love

    def set_lover(self, girl):
        self.__love = girl


def single_class_decorator(cls):
    # 单例类装饰器
    instance = {}

    def inner(*args, **kwargs):

        if cls not in instance.keys():

            instance[cls] = cls(*args, **kwargs)

        return instance[cls]

    return inner


@single_class_decorator
class A:

    pass


if __name__ == '__main__':
    wcy = MyLove('jn')
    wcy.get_lover()
    # 不会因为遇见不同女孩变心
    kw = MyLove('sx')
    kw.get_lover()

    # 除非自己变心
    print('change to sx by self')
    kw.set_lover('sx')
    kw.get_lover()
    wcy.get_lover()
    print(wcy is kw)

    a = A()
    b = A()
    print(a is b)





